import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/course.dart';
import 'package:kxy_flutter_app/view/course/course_detail_view.dart';
import 'package:line_awesome_icons/line_awesome_icons.dart';

class CourseColumnItemWidget extends StatefulWidget {
  final CourseProfile course;
  final double width;

  const CourseColumnItemWidget({
    Key key,
    @required this.course,
    @required this.width,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _CourseColumnItemWidgetState();
  }
}

class _CourseColumnItemWidgetState extends State<CourseColumnItemWidget> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () async {
        await Navigator.push(
          context,
          MaterialPageRoute(
            builder: (cxt) => CourseDetailView(courseId: widget.course.id),
          ),
        );

        widget.course.viewCount++;
        await refreshStatus();
      },
      child: Container(
        width: widget.width / 2,
        child: Column(
          children: [
            imgWidget(widget.course.imgUrl),
            titleWidget(widget.course),
            infoWidget(widget.course),
          ],
        ),
      ),
    );
  }

  Widget imgWidget(String imgUrl) {
    var boxShadow = [
      BoxShadow(
        color: Color.fromRGBO(240, 240, 240, 1),
        offset: Offset(1, 1),
      ),
      BoxShadow(
        color: Color.fromRGBO(240, 240, 240, 1),
        offset: Offset(-1, -1),
      ),
    ];

    return AspectRatio(
      aspectRatio: 16 / 9,
      child: Container(
        decoration: BoxDecoration(
          color: Color.fromRGBO(240, 240, 240, 1),
          borderRadius: BorderRadius.circular(5),
          boxShadow: boxShadow,
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(5),
          child: CachedNetworkImage(
            imageUrl: imgUrl,
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  Widget infoWidget(CourseProfile course) {
    var format = new DateFormat('yyyy-MM-dd');
    var style = TextStyle(fontSize: 11, color: Colors.black54);
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Icon(
                LineAwesomeIcons.clock_o,
                size: 16,
                color: Colors.black54,
              ),
              Text(
                format.format(course.publishDate),
                style: style,
              ),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Icon(
                LineAwesomeIcons.user,
                size: 16,
                color: Colors.black54,
              ),
              Text(
                course.viewCount.toString(),
                style: style,
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget titleWidget(CourseProfile course) {
    return Container(
      // height: 40,
      alignment: Alignment.topLeft,
      margin: EdgeInsets.symmetric(vertical: 5),
      child: RichText(
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        softWrap: true,
        text: TextSpan(children: [
          WidgetSpan(child: statusTagWidget(course.status)),
          TextSpan(
            text: course.title,
            style: TextStyle(
              fontSize: 14,
              color: Colors.black87,
              height: 1.2,
            ),
          ),
        ]),
      ),
    );
  }

  Widget statusTagWidget(CourseStatus status) {
    Color color;
    String text;
    if (status == CourseStatus.NotStarted) {
      color = Color.fromRGBO(255, 199, 110, 1);
      text = '未学习';
    }

    if (status == CourseStatus.Learning) {
      color = Color.fromRGBO(102, 211, 159, 1);
      text = '未完成';
    }

    if (status == CourseStatus.Completed) {
      color = Color.fromRGBO(91, 161, 252, 1);
      text = '已完成';
    }

    return Container(
      height: 15,
      width: 40,
      alignment: Alignment.center,
      margin: EdgeInsets.only(right: 3),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(3),
      ),
      child: Text(
        text,
        style: TextStyle(
          color: Colors.white,
          fontSize: 11,
        ),
      ),
    );
  }

  Future refreshStatus() async {
    var res = await Http.instance.post('/train-app/courseapp/courseStatus', params: {
      'courseId': widget.course.id,
      'userId': Auth.instance.userId,
    });

    if (res.code == 200) {
      var resStatus = CourseStatus.values[res.data];
      setState(() {
        widget.course.status = resStatus;
      });
    }
  }
}
